#include "GY_GraphicsViewBP.h"
#include <QScrollBar>
#include <QContextMenuEvent>
#include <QLineEdit>
#include <QtDebug>
#include <QTextEdit>
#include <QPushButton>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QMessageBox>
#include <QDir>
#include <cmath>

#include "GY_PopupMenu.h"
#include "GY_DiagramScene.h"
#include "GY_ValuePanel.h"
#include "ui_GY_ValuePanel.h"
#include "GY_DiagramItem.h"

GY_GraphicsViewBP::GY_GraphicsViewBP(QWidget *parent) : QGraphicsView(parent)
{
    panel=nullptr;
    itemSel=nullptr;
    scene = nullptr;
    ctrlKey=false;
    setRenderHint(QPainter::Antialiasing);
    //setBackgroundBrush(QBrush(QColor(128,128,128)));
    setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);  //
    horizontalScrollBar()->setEnabled(true);
//    verticalScrollBar()->setEnabled(true);
//    setContextMenuPolicy();
    setDragMode(QGraphicsView::RubberBandDrag);  //框选
//    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);//拖动时残影的解决

    //读取配置文件
    QFile config(configFileName);
    if(config.open(QIODevice::ReadOnly)){
        QByteArray fileData = config.readAll();
        config.close();
        QJsonParseError e;
        QJsonDocument doc;
        doc = QJsonDocument::fromJson(fileData,&e);
        if(e.error == QJsonParseError::NoError){
            configFile = doc.object();
            schemeFileDir = configFile["schemeFileDir"].toString();
        }
    }

    //确保schemeFileDir的目录存在
    if (QDir(schemeFileDir).exists() == false){  //
        QDir().mkdir(schemeFileDir);
    }


    pMenu = new GY_PopupMenu(this);  //改变菜单文件数据后须重启
    pMenu->hide();



    QAction* toFrontAction = new QAction(QIcon(":/images/bringtofront.png"),
                                tr("最前显示"), this);
//    toFrontAction->setShortcut(tr("Ctrl+F"));
    toFrontAction->setStatusTip(tr("显示到最前面"));
    connect(toFrontAction, SIGNAL(triggered()), this, SLOT(bringToFront()));

    QAction* sendBackAction = new QAction(QIcon(":/images/sendtoback.png"), tr("后面显示"), this);
//    sendBackAction->setShortcut(tr("Ctrl+T"));
    sendBackAction->setStatusTip(tr("显示到后面"));
    connect(sendBackAction, SIGNAL(triggered()), this, SLOT(sendToBack()));

    QAction* deleteAction = new QAction(QIcon(":/images/delete.png"), tr("删除"), this);
    deleteAction->setShortcut(tr("Delete"));  //
    deleteAction->setStatusTip(tr("从蓝图删除"));
    connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteItem()));


    itemMenu = new QMenu(this);
    itemMenu->addAction(deleteAction);
    itemMenu->addSeparator();
    itemMenu->addAction(toFrontAction);
    itemMenu->addAction(sendBackAction);


    NewScene();




}
GY_GraphicsViewBP::~GY_GraphicsViewBP(){

}

void GY_GraphicsViewBP::contextMenuEvent(QContextMenuEvent *event){

    //emit sigPopupMenu(event->pos());  //自定义信号编译不过重启电脑，重新编译
    //emit customContextMenuRequested(event->pos());

    //if(((DiagramScene*)scene())->selectedItems().count())  //不正常
    QGraphicsItem* item = scene->SelectedItem(mapToScene(event->pos()));
    if(item)  //
    {
        //qDebug()<<"item->type()"<<item->type();  //65536
        if(GY_Arrow::Type == item->type()
        || GY_DiagramItem::Type == item->type()){
            itemMenu->move(this->cursor().pos());
            itemMenu->show();

            HidePopupMenu();
        }
    }else{
        if(!rightBtnMoveRelease){
            GetMenu()->move(event->pos());
            GetMenu()->show();
        }
        scene->setAddItemAtPoint(this->mapToScene(event->pos()));

    }
}

void GY_GraphicsViewBP::HidePopupMenu(){
    if(!pMenu){return;}
    pMenu->hide();

}

void GY_GraphicsViewBP::ShowPopupMenu(QPointF point){
    pMenu->move(this->mapFromScene(point));
    pMenu->show();
}

void GY_GraphicsViewBP::deleteItem()
{
    QList<QGraphicsItem *> selectedItems = scene->selectedItems();
    for (QGraphicsItem *item : qAsConst(selectedItems)) {
        if (item->type() == GY_Arrow::Type) {
            if(scene->getSelLine() == item){
                if(scene->getSelLine()->startPort()){
                    scene->getSelLine()->startPort()->setLinkedBySelLine(false);
                    scene->getSelLine()->startPort()->update();  //重绘
                }
                if(scene->getSelLine()->endPort()){
                    scene->getSelLine()->endPort()->setLinkedBySelLine(false);
                    scene->getSelLine()->endPort()->update();  //重绘
                }

                scene->setSelLine(nullptr);  //保存选中线的指针置空

            }
            scene->removeItem(item);
            GY_Arrow *arrow = qgraphicsitem_cast<GY_Arrow *>(item);
            arrow->startPort()->SetLineCount(-1);
            arrow->endPort()->SetLineCount(-1);
            ((GY_DiagramItem*)arrow->startPort()->parentItem())->removeArrow(arrow);
            ((GY_DiagramItem*)arrow->endPort()->parentItem())->removeArrow(arrow);
            delete item;
            item = nullptr;
        }
    }

    selectedItems = scene->selectedItems();
    for (QGraphicsItem *item : qAsConst(selectedItems)) {
         if (item->type() == GY_DiagramItem::Type){
             qgraphicsitem_cast<GY_DiagramItem *>(item)->removeArrows();
         }
         scene->removeItem(item);

         if(itemSel==item){
            this->HidePanel();
         }

         delete item;
         item = nullptr;
    }
}

void GY_GraphicsViewBP::bringToFront()
{
    if (scene->selectedItems().isEmpty())
        return;

    QGraphicsItem *selectedItem = scene->selectedItems().first();
    const QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems();

    qreal zValue = 0;
    for (const QGraphicsItem *item : overlapItems) {
        if (item->zValue() >= zValue && item->type() == GY_DiagramItem::Type)
            zValue = item->zValue() + 0.1;
    }
    selectedItem->setZValue(zValue);
}

void GY_GraphicsViewBP::sendToBack()
{
    if (scene->selectedItems().isEmpty())
        return;

    QGraphicsItem *selectedItem = scene->selectedItems().first();
    const QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems();

    qreal zValue = 0;
    for (const QGraphicsItem *item : overlapItems) {
        if (item->zValue() <= zValue && item->type() == GY_DiagramItem::Type)
            zValue = item->zValue() - 0.1;
    }
    selectedItem->setZValue(zValue);
}

void GY_GraphicsViewBP::ShowPanel(GY_DiagramItem* item){
    itemSel = item;

    if(!panel){
        panel = new GY_ValuePanel(this);
    }

    if(panel){
        panel->GetUi()->treeWidget->clear();

        if(item->diagramType()==GY_DiagramItem::Input){  //不使用

            int x = this->width() - panel->width();
            panel->setGeometry(x,0,panel->width(),this->height());
            panel->show();


            for(GY_PortItem* port : item->GetPortsDataO()){
                if(port->GetPortType()==GY_PortItem::dataO){
                    QTreeWidgetItem* parent = new QTreeWidgetItem(panel->GetUi()->treeWidget,QStringList(port->GetName()));
                    panel->GetUi()->treeWidget->addTopLevelItem(parent);
                    //QTextEdit* name = new QTextEdit(panel->GetUi()->treeWidget);
                    //name->setText(port->GetName());
                    //connect(name,SIGNAL(textChanged()),this,SLOT(SetPortName()),Qt::UniqueConnection);
                    QLineEdit* value = new QLineEdit(panel->GetUi()->treeWidget);
                    value->setText(port->GetValue());
                    connect(value,SIGNAL(textChanged(QString)),this,SLOT(SetPortValue(QString)),Qt::UniqueConnection);
                    //qDebug()<<port->GetValue();
                    panel->GetUi()->treeWidget->setItemWidget(parent,1,value);
                }

            }


        }else

        if(item->diagramType()==GY_DiagramItem::Step
        || item->diagramType()==GY_DiagramItem::Branch){

            int x = this->width() - panel->width();
            panel->setGeometry(x,0,panel->width(),this->height());
            panel->show();


            for(GY_PortItem* port : item->GetPortsDataI()){
                //if(port->GetPortType()==PortItem::dataI){
                    QTreeWidgetItem* parent = new QTreeWidgetItem(panel->GetUi()->treeWidget,QStringList(port->GetName()));
                    panel->GetUi()->treeWidget->addTopLevelItem(parent);

                    QLineEdit* value = new QLineEdit(panel->GetUi()->treeWidget);
                    value->setText(port->GetValue());
                    value->setDragEnabled(true);

                    connect(value,SIGNAL(textChanged(QString)),this,SLOT(SetPortValue(QString)),Qt::UniqueConnection);
                    panel->GetUi()->treeWidget->setItemWidget(parent,1,value);
/*
                    QPushButton* selValue = new QPushButton(panel->GetUi()->treeWidget);
                    selValue->setText("选择");
                    connect(selValue,SIGNAL(clicked()),this,SLOT(SelValue()),Qt::UniqueConnection);
                    panel->GetUi()->treeWidget->setItemWidget(parent,2,selValue);

                    QLineEdit* strSignals = new QLineEdit(panel->GetUi()->treeWidget);
                    strSignals->setText(port->getStrSignals());
                    connect(strSignals,SIGNAL(textChanged(QString)),this,SLOT(SetSignals(QString)),Qt::UniqueConnection);
                    panel->GetUi()->treeWidget->setItemWidget(parent,3,strSignals);
//*/

                //}

            }


        }


    }
}


void GY_GraphicsViewBP::HidePanel(){
    if(panel){
        delete panel;
        panel = nullptr;
    }

    if(itemSel){itemSel =   nullptr;}
}

void GY_GraphicsViewBP::mousePressEvent(QMouseEvent *event)
{

    rightBtnMoveRelease = false;
    if(event->button() == Qt::RightButton){
        setDragMode(QGraphicsView::NoDrag);  //ScrollHandDrag  //NoDrag
        if(scene->itemAt(mapToScene(event->pos()), transform()) == nullptr){  //没有选中任何图元
            rightBtnDownPos = event->pos();  //qDebug() << "\n===rightBtnDownPos"<<rightBtnDownPos<<"\n";
            rightBtnDown = true;
//            m_CenterAnchor = mapToScene(rightBtnDownPos) - rightBtnDownPos + QPointF(width() / 2, height() / 2);
        }
    }

    QGraphicsView::mousePressEvent(event);
}

void GY_GraphicsViewBP::mouseMoveEvent(QMouseEvent *event)
{
    QGraphicsView::mouseMoveEvent(event);

    if(rightBtnDown){
        rightBtnMove = true;

//        QPointF ptNow = mapToScene(event->pos());
//        QPointF ptMove = ptNow - mapToScene(rightBtnDownPos);
//        //鼠标当前的点作为定位点
//        setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
//        QPoint nowCenter(-ptMove.x(),-ptMove.y());
//        centerOn(nowCenter);
//        setTransformationAnchor(QGraphicsView::AnchorViewCenter);

//        QPoint posPoint = event->pos();
//        QPointF offsetPos = posPoint - rightBtnDownPos;
//        setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
//        QPointF pf = m_CenterAnchor - offsetPos;
//        //上下反向
////        pf.ry()*=-1;
//        centerOn(pf);


        QPoint ptNow = event->pos();
        QPoint ptMove = ptNow - rightBtnDownPos;
//        horizontalScrollBar()->setValue(horizontalScrollBar()->value() - ptMove.x());
//        verticalScrollBar()->setValue(verticalScrollBar()->value() - ptMove.y());

        QRectF rc = sceneRect();
        setSceneRect(rc.x() - ptMove.x(), rc.y() - ptMove.y(), rc.width(), rc.height());
        rightBtnDownPos = event->pos();

    }


}

void GY_GraphicsViewBP::mouseReleaseEvent(QMouseEvent *event)
{
    QGraphicsView::mouseReleaseEvent(event);
    if(event->button() == Qt::RightButton){
        setDragMode(QGraphicsView::RubberBandDrag);  //框选
        rightBtnDown = false;
        if(rightBtnMove){
            rightBtnMove = false;
            rightBtnMoveRelease = true;
        }

    }

}

void GY_GraphicsViewBP::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Control){
        ctrlKey=true;
    }
    else if(event->key() == Qt::Key_Delete){
        deleteItem();
    }


}

void GY_GraphicsViewBP::keyReleaseEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Control){
        ctrlKey=false;
    }
}


void GY_GraphicsViewBP::resizeEvent(QResizeEvent *event){
    QGraphicsView::resizeEvent(event);

    if(panel){
        int x = this->width() - panel->width();
        panel->setGeometry(x,0,panel->width(),this->height());
    }
}

void GY_GraphicsViewBP::wheelEvent(QWheelEvent *event)
{
    if(ctrlKey){
        scene->SetSceneScale(event->delta());
    }
}

void GY_GraphicsViewBP::SetPortValue(QString value){
    if(panel){
        QString portName;
        portName = panel->GetUi()->treeWidget->currentItem()->data(0,Qt::DisplayRole).toString();

        switch(itemSel->diagramType()){
        case GY_DiagramItem::Input:
            for(GY_PortItem* port : itemSel->GetPortsDataO()){
                if(port->GetName()==portName){
                    port->SetValue(value);
                    break;
                }
            }
            break;
        case GY_DiagramItem::Step:
        case GY_DiagramItem::Branch:
            for(GY_PortItem* port : itemSel->GetPortsDataI()){
                if(port->GetName()==portName){
                    port->SetValue(value);
                    break;
                }
            }
            break;
        default:
            break;
        }



    }
}

void GY_GraphicsViewBP::setItemFontPixelSize(int value)
{
    itemFontPixelSize = value;
}

void GY_GraphicsViewBP::setItemTextColor(const QColor &value)
{
    itemTextColor = value;
}

void GY_GraphicsViewBP::setSchemeFileDir(const QString &value)
{
    schemeFileDir = value;

    //保存到配置文件
    configFile["schemeFileDir"] = schemeFileDir;

    QFile file(configFileName);
    QByteArray fileData;
    QJsonDocument doc;
    doc.setObject(configFile);
    fileData = doc.toJson(QJsonDocument::Compact);
    QString jsonStr(fileData);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream in(&file);
        in.setCodec("UTF-8");  //中文
        in << jsonStr;
        file.close();
    }
}

QJsonObject& GY_GraphicsViewBP::getSchemeFile()
{
    return schemeFile;
}

QString GY_GraphicsViewBP::getSchemeFilePath() const
{
    return schemeFileDir + "/" + schemeFileName;
}

void GY_GraphicsViewBP::setSchemeFileName(const QString &value)
{
    schemeFileName = value;
}

void GY_GraphicsViewBP::loadSchemeFile()
{
    QFile loadFile(getSchemeFilePath());
    if(loadFile.open(QIODevice::ReadOnly)){
        QByteArray fileData = loadFile.readAll();
        loadFile.close();
        QJsonParseError e;
        QJsonDocument doc;
        doc = QJsonDocument::fromJson(fileData,&e);
        if(e.error == QJsonParseError::NoError){
            schemeFile = doc.object();
        }
    }
}

QJsonArray GY_GraphicsViewBP::getSchemes()
{
    QJsonArray schemes;
    schemes = schemeFile["root"].toArray();
    return schemes;
}

void GY_GraphicsViewBP::loadScheme(QString groupName, QString schemeName)
{
    QJsonArray array = schemeFile["root"].toArray();
    for(QJsonValue val : array){
        if(val.toObject()["group"].toString()==groupName){
            for(QJsonValue v: val.toObject()["item"].toArray()){
                if(v.toObject()["name"].toString()==schemeName){

                    //if(v.toObject()["item"].toArray().size()){ ui->graphicsView->GetScene()->clear();}

                    for(QJsonValue vi: v.toObject()["item"].toArray()){

                        QJsonDocument d;
                        d.setObject(vi.toObject());

                        GetScene()->SlotInsertItem(QString(d.toJson(QJsonDocument::Compact)),GY_DiagramScene::InsertItem);
                    }

                    //画线
                    for(QJsonValue vi: v.toObject()["line"].toArray()){

                        QJsonDocument d;
                        d.setObject(vi.toObject());

                        GetScene()->SlotInsertItem(QString(d.toJson(QJsonDocument::Compact)),GY_DiagramScene::InsertLine);
                    }
                    break;
                }
            }
            break;
        }
    }
    if(!GetScene()->items().size()){
        NewSceneSE();
    }

    //所有DiagramItem::ItemChange()以显示线条，否则不能正常显示
    for(QGraphicsItem* item : GetScene()->items()){
        if(item->type()==GY_DiagramItem::Type){
            ((GY_DiagramItem*)item)->ItemChange();
        }
    }

    //缩放scene显示所有图形
    QSize vs = viewport()->size();
    QPointF vp1 = mapToScene(0,0);
    QPointF vp2 = mapToScene(vs.width(),vs.height());
    QRectF vr = QRectF(vp1,vp2);
    QRectF sr = sceneRect();
    sr = GetScene()->itemsBoundingRect();
//        qDebug()<<"sceneRect"<<vr;
//        qDebug()<<"sceneRect"<<sr;

    while(!vr.contains(sr)){

        if(vr.width() >= sr.width() && vr.height() >= sr.height()){  //调整位置
            viewport()->move(sr.x()-vr.x(),sr.y()-vr.y());

            break;
        }
        else{

            qreal value = GetScene()->GetScale() - GetScene()->GetMiniScale();

            if( fabs(value) < 0.000001 ){
                break;  //缩到最小仍无法显示全部场景
            }
            else {
                GetScene()->SetSceneScale(-1);  //缩小场景
                //更新判断条件数据
                vs = viewport()->size();
                vp1 = mapToScene(0,0);
                vp2 = mapToScene(vs.width(),vs.height());
                vr = QRectF(vp1,vp2);
                sr = sceneRect();
                sr = GetScene()->itemsBoundingRect();
                continue;  //缩小后或再次进入循环调整位置
            }
        }
    }

}

bool GY_GraphicsViewBP::saveAsScheme(QString groupName, QString schemeName, QString saveAsSchemeName)
{
    QFile file(getSchemeFilePath());
    QByteArray fileData;
    QJsonDocument doc;
    QJsonArray array = schemeFile["root"].toArray();

    QJsonObject schemeObj;
    for(int j = 0;j < array.size();++j){
        QJsonObject groupObj = array[j].toObject();
        if(groupObj["group"].toString()==groupName){

            QJsonArray itemArray = groupObj["item"].toArray();

            for(QJsonValue item: itemArray){
                if(saveAsSchemeName == item.toObject()["name"].toString()){
                    QMessageBox::information(this,"提示","方案名已存在，请重新另存");
                    return false;
                }
            }

            //
            for(QJsonValue item: itemArray){
                if(schemeName == item.toObject()["name"].toString()){
                    schemeObj = item.toObject();
                    schemeObj["name"]=saveAsSchemeName;
                    itemArray.append(schemeObj);

                    groupObj["item"] = itemArray;

                    array[j] = groupObj;

                    break;
                }
            }



            break;
        }
    }

    schemeFile["root"] = array;  //qDebug()<<array;


    doc.setObject(schemeFile);
    fileData = doc.toJson(QJsonDocument::Compact);
    QString jsonStr(fileData);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream in(&file);
        in.setCodec("UTF-8");  //中文
        in << jsonStr;
        file.close();
    }
    return true;
}

void GY_GraphicsViewBP::resetScene()
{

    QList<QGraphicsItem *> items = scene->items();
    for (QGraphicsItem *item : qAsConst(items)) {
        if (item->type() == GY_Arrow::Type) {
            if(scene->getSelLine() == item){
                if(scene->getSelLine()->startPort()){
                    scene->getSelLine()->startPort()->setLinkedBySelLine(false);
                    scene->getSelLine()->startPort()->update();  //重绘
                }
                if(scene->getSelLine()->endPort()){
                    scene->getSelLine()->endPort()->setLinkedBySelLine(false);
                    scene->getSelLine()->endPort()->update();  //重绘
                }

                scene->setSelLine(nullptr);  //保存选中线的指针置空

            }
            scene->removeItem(item);
            GY_Arrow *arrow = qgraphicsitem_cast<GY_Arrow *>(item);
            arrow->startPort()->SetLineCount(-1);
            arrow->endPort()->SetLineCount(-1);
            ((GY_DiagramItem*)arrow->startPort()->parentItem())->removeArrow(arrow);
            ((GY_DiagramItem*)arrow->endPort()->parentItem())->removeArrow(arrow);
            delete item;
            item = nullptr;
        }
    }

    items = scene->items();
    for (QGraphicsItem *item : qAsConst(items)) {
         if (item->type() == GY_DiagramItem::Type){
             GY_DiagramItem * diagram = qgraphicsitem_cast<GY_DiagramItem *>(item);
             if(GY_DiagramItem::StartEnd != diagram->diagramType()){  //保留开始和结束图元
                 diagram->removeArrows();

                 scene->removeItem(item);

                 if(itemSel==item){
                    this->HidePanel();
                 }

                 delete item;
                 item = nullptr;
             }
         }

    }
}

void GY_GraphicsViewBP::saveScheme(QString groupName, QString schemeName)
{
    scene->SaveScene(groupName, schemeName, schemeFile, getSchemeFilePath());
}

void GY_GraphicsViewBP::setBackgroundBrush(const QBrush &brush)
{
    sceneBgBrush = brush;
}

void GY_GraphicsViewBP::setForegroundBrush(const QBrush &brush)
{
    sceneFgBrush = brush;
}

void GY_GraphicsViewBP::setItemBgColor(const QColor & color)
{
    itemBgColor = color;
}

bool GY_GraphicsViewBP::addScheme(QString groupName, QString schemeName)
{
    QFile file(getSchemeFilePath());
    QByteArray fileData;
    QJsonDocument doc;
    QJsonArray array = schemeFile["root"].toArray();

    QJsonObject schemeObj;
    schemeObj["name"]=schemeName;
    QJsonArray ItemArray;
    QJsonArray LineArray;
    schemeObj["item"] = ItemArray;
    schemeObj["line"] = LineArray;
    for(int j = 0;j < array.size();++j){
        QJsonObject groupObj = array[j].toObject();
        if(groupObj["group"].toString()==groupName){

            QJsonArray itemArray = groupObj["item"].toArray();

            for(QJsonValue item: itemArray){
                if(schemeName == item.toObject()["name"].toString()){
                    QMessageBox::information(this,"提示","方案名已存在，请重新添加");
                    return false;
                }
            }

            itemArray.append(schemeObj);

            groupObj["item"] = itemArray;

            array[j] = groupObj;

            break;
        }
    }

    schemeFile["root"] = array;  //qDebug()<<array;


    doc.setObject(schemeFile);
    fileData = doc.toJson(QJsonDocument::Compact);
    QString jsonStr(fileData);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream in(&file);
        in.setCodec("UTF-8");  //中文
        in << jsonStr;
        file.close();
    }

    return true;
}

bool GY_GraphicsViewBP::getRightBtnMoveRelease() const
{
    return rightBtnMoveRelease;
}


void GY_GraphicsViewBP::NewScene(){
    if(scene){

        delete scene;
        scene = nullptr;
    }
    scene = new GY_DiagramScene(GetItemMenu(), this);
//    scene->setSceneRect(QRectF());  //unset or null QRectF to set the largest bounding rect of all items
    scene->setSceneRect(QRectF(0,0,1000,1000));  //必须设置，否则会自动对准viewport造成item位置改变错觉
    scene->setBackgroundBrush(sceneBgBrush);
    scene->setForegroundBrush(sceneFgBrush);
    scene->setItemColor(itemBgColor);
    scene->setItemTextColor(itemTextColor);
    scene->setItemFontPixelSize(itemFontPixelSize);
    scene->SetSceneScale(0);  //重置缩放

    setScene(scene);
    setSceneRect(QRectF(0,0,1000,1000));  //右键拖拽整个场景位置
    connect(scene,SIGNAL(sigPopupMenu(QPointF)),this,SLOT(ShowPopupMenu(QPointF)),Qt::UniqueConnection);
    connect(scene,SIGNAL(sigHidePopupMenu()),this,SLOT(HidePopupMenu()),Qt::UniqueConnection);
    connect(GetMenu(),SIGNAL(InsertItem(QString,GY_DiagramScene::Mode)),scene,SLOT(SlotInsertItem(QString,GY_DiagramScene::Mode)),Qt::UniqueConnection);


}

void GY_GraphicsViewBP::NewSceneSE()
{
    NewScene();
    //添加开始和结束图元
    scene->setAddItemAtPoint(sceneRect().center());  //屏幕外的位置可能会有背景显示问题
    emit pMenu->InsertItem(pMenu->findItemJsonStr("Start"));
    emit pMenu->InsertItem(pMenu->findItemJsonStr("End"));
}

int GY_GraphicsViewBP::sceneItemCount()
{
    return scene->items().count();
}

